package cn.itmtr.screenshot;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.swing.DesktopUtil;
import cn.hutool.core.util.StrUtil;

import java.io.IOException;

/**
 * windows截屏
 *
 * @author mtr
 * @since 2021-09-24
 */
public class ScreenshotWindowsApplication {

    /**
     * 插件引入地址
     */
    private static final String PHANTOMJS_EXE = "bin/phantomjs.exe";
    /**
     * 截图工具引入地址
     */
    private static final String PHANTOMJS_RASTERIZE_JS = "examples/rasterize.js";


    public static void main(String[] args) throws IOException {
//        String phantomjsPath = "E:/itmtr/screenshot/src/main/resources/phantomjs/phantomjs-2.1.1-windows/";
        String phantomjsPath = "C:/Users/AOC/Desktop/phantomjs-2.1.1-windows/";
        String imagePath = "C:/Users/AOC/Desktop/test.jpg";
        String url = "http://www.baidu.com/";
        screenshot(phantomjsPath, url, imagePath);
        DesktopUtil.open(FileUtil.file(imagePath));
    }


    public static void screenshot(String phantomjsPath, String url, String imagePath) throws IOException {
        // Java中使用Runtime和Process类运行外部程序
        String cmd = cmd(phantomjsPath, url, imagePath);
        System.out.println(cmd);
        Process process = Runtime.getRuntime().exec(cmd);
        // 执行结果
        FileUtil.writeFromStream(process.getInputStream(), imagePath);
        process.destroy();
    }

    /**
     * 获取要执行的命令
     *
     * @param phantomjsPath phantomjs路径
     * @param url           要生成的网址链接
     * @param imagePath     生成图片路径
     * @return java.lang.String
     * @author mtr
     * @date 2021/9/24
     */
    public static String cmd(String phantomjsPath, String url, String imagePath) {
        String exe = phantomjsPath + PHANTOMJS_EXE;
        String js = phantomjsPath + PHANTOMJS_RASTERIZE_JS;
        return StrUtil.format("{} {} {} {} 1440px*960px", exe, js, url, imagePath);
    }

}
